﻿using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeHeng_Mes.Utils;
using System.Reflection;
using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.Singleton;
using SqlSugar;
using MappingTable = DeHeng_Mes.Utils.MappingTable;
using DeHeng_Mes.Model.OrderSingleton;

namespace DeHeng_Mes.Thread
{
    public class PlcCollectionData
    {
        #region 全局成员
        List<PlcOrderConfigModel> readPlcList = PlcOrderConfigModelList.ReadPlcList;
        LinePlcToMes LinePlcToMes = new LinePlcToMes();
        PlcDao plcDao = new PlcDao();
        #endregion

        /// <summary>
        /// Plc交互轮询
        /// </summary>
        /// <returns></returns>
        public async Task CollectionTask()
        {
            Tools.ProduceLogText("启动Plc交互线程成功！");

            while (true)
            {
                await Task.Delay(100);

                if (readPlcList?.Count > 0)
                {
                    //遍历订单模型，取出该模型下挂的所有Plc处理数据
                    foreach (var orderModel in readPlcList)
                    {
                        //判断当前订单模型是否处于处理状态，如果处于正在处理状态那么不会继续创建
                        if (orderModel.plc.IsConnected)
                        {
                            try
                            {

                                // 获取Plc数据实例与实例类型  
                                Dictionary<object, Type> dictionary = MappingTable.PlcMapping(orderModel.plc, orderModel.PlcName);

                                // 处理采集数据
                                LinePlcToMes.ProcessOkStatus(dictionary, orderModel);

                            }
                            catch (Exception ex)
                            {
                                Tools.ProduceLogTextError("数据读取执行失败，原因是：" + ex.Message);
                            }
                        }
                    }
                }
            }
        }
    }
}
